#include "GunObject.h"
#include "SpriteMaker.h"
GunObject::GunObject(b2World *_World) :BaseObject(_World)
{
}

GunObject::~GunObject()
{
}

void GunObject::init(SpriteBatchNode* _Spritebatch, SpriteFrameCache* _Cache, Sprite *_Parent)
{
	mId = OBJECT_GUN;
	mIsAction = true;
	mIsCollision = false;

	mBody = new GunBody(mWorld, b2_staticBody);
	mBody->mColBody->SetUserData(this);
	mSprite = SpriteMaker::makeSprite(_Spritebatch, "gun_01.png");
	mSprite->setScaleX(0.5f);
	mAnimation = SpriteMaker::makeAnimation(_Cache, "gun", 1, 4, 1.f);
	mSprite->runAction(mAnimation);
}

void GunObject::update(float dt)
{
	draw();
}

void GunObject::draw()
{
	if (mIsAction == false)
	{
		mSprite->setPosition(Vec2(mBody->getPosition().x, mBody->getPosition().y));
		mSprite->setRotation(mBody->getAngle()*-Define::RAD_TO_DEG);
	}
	else
	{
		mBody->setPosition(b2Vec2(mSprite->getPosition().x, mSprite->getPosition().y));
		mBody->setAngle(mSprite->getRotation()*-Define::DEG_TO_RAD);
	}
}

void GunObject::destroy()
{
	
}

void GunObject::onCollisionWith(BaseObject *_Object)
{
	switch (_Object->mId)
	{
	case OBJECT_BULLET:
		if (mIsCollision == false)
		{
			mIsAction = true;
			mIsCollision = true;
			makeJointWithBullet(_Object);

			auto actionBy = RotateBy::create(1, 90);
			this->mSprite->runAction(actionBy);
		}
		break;

	}
}

void GunObject::initAction()
{
	mAction = NULL;
}

void GunObject::makeJointWithBullet(BaseObject* bullet)
{
	b2Body *bodyA = bullet->mBody->mShaBody;
	b2Body *bodyB = this->mBody->mColBody;
	b2Vec2 worldCoordsAnchorPointA = bodyA->GetWorldPoint(b2Vec2(0, 0));
	b2Vec2 worldCoordsAnchorPointB = bodyB->GetWorldPoint(b2Vec2(0, 0));

	b2WeldJointDef weldJointDef;
	weldJointDef.bodyA = bodyA;
	weldJointDef.bodyB = bodyB;
	weldJointDef.Initialize(bodyA, bodyB, worldCoordsAnchorPointB);
	((BulletObject*)bullet)->mListJoint.push_back(mWorld->CreateJoint(&weldJointDef));
}
